import { PrismaService } from '@/prisma/prisma.service';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { user } from '@prisma/client';
import axios from 'axios';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';

@Injectable()
export class AuthService {
  constructor(
    private config: ConfigService,
    private prisma: PrismaService,
    private jwt: JwtService,
  ) {}
  async create(openid: string) {
    const user = await this.prisma.user.create({
      data: {
        openid,
      },
    });
    return this.token(user);
  }
  async getWxOpenId(code: string) {
    const result = await axios.get(
      'https://api.weixin.qq.com/sns/jscode2session',
      {
        params: {
          appid: this.config.get('WX_APPID'),
          secret: this.config.get('WX_SECRET'),
          js_code: code,
          grant_type: 'authorization_code',
        },
      },
    );
    return result.data.openid;
  }
  // 查询数据库某表是否存在某字段
  async isExist(
    table: string,
    field: string,
    content: string,
  ): Promise<boolean | user> {
    const result = await this.prisma[table].findFirst({
      where: {
        [field]: content + '',
      },
    });
    return result;
  }

  async token({ id, openid }: user) {
    return {
      token: await this.jwt.signAsync({ id, openid }),
    };
  }
  async findUseinfo(req) {
    const result = await this.prisma.user.findUnique({
      select: {
        heade: true,
        nickName: true,
      },
      where: {
        id: req.user.id,
      },
    });
    return result;
  }

  findOne(id: number) {
    return `This action returns a #${id} auth`;
  }

  async update(updateAuthDto: UpdateAuthDto, req) {
    const result = await this.prisma.user.findUnique({
      where: {
        id: req.user.id,
      },
    });
    const updateValue = { ...result, ...updateAuthDto };
    const upDataResult = await this.prisma.user.update({
      where: {
        id: req.user.id,
      },
      data: updateValue,
    });
    return upDataResult;
  }

  remove(id: number) {
    return `This action removes a #${id} auth`;
  }
}
